package com.betterlife.todolist.db;


import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.betterlife.todolist.entity.Task;

public class DBManager {
	private DBHelper helper;
	private SQLiteDatabase db;
	
	public DBManager(Context context) {
		helper = new DBHelper(context);
		//因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
		//所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
		db = helper.getWritableDatabase();
	}
	
	/**
	 * add persons
	 * @param persons
	 */
	public void add(List<Task> tasks) {
        db.beginTransaction();	//开始事务
        try {
        	for (Task task : tasks) {
        		
        		db.execSQL("INSERT INTO task VALUES(null, ?, ?, ?, ?, ?, ?)", 
        				new Object[]{task.getTitle(), task.getContent(),task.getIsLoop(),task.getReminderDateTime()+"", task.getCreateDate()+"", task.getLastUpdateDate()+""});
        	}
        	db.setTransactionSuccessful();	//设置事务成功完成
        } finally {
        	db.endTransaction();	//结束事务
        }
	}
	
	/**
	 * update person's age
	 * @param person
	 */
	public void update(Task task) {
		ContentValues cv = new ContentValues();
		cv.put("title", task.getTitle());
		db.update("task", cv, "_id = ?", new String[]{ task.getId()+""});
	}
	
	/**
	 * delete old person
	 * @param person
	 */
	public void deleteOldTask(Task task) {
		db.delete("task", "_id <= ?", new String[]{String.valueOf(task.getId())});
	}
	
	/**
	 * query all persons, return list
	 * @return List<Person>
	 */
	public List<Task> query() {
		ArrayList<Task> tasks = new ArrayList<Task>();
		Cursor c = queryTheCursor();
        while (c.moveToNext()) {
        	Task task = new Task();
        	task.setId(c.getInt(c.getColumnIndex("_id")));
        	task.setTitle(c.getString(c.getColumnIndex("title")));
        	task.setContent(c.getString(c.getColumnIndex("content")));
        	tasks.add(task);
        }
        c.close();
        return tasks;
	}
	
	/**
	 * query all persons, return cursor
	 * @return	Cursor
	 */
	public Cursor queryTheCursor() {
        Cursor c = db.rawQuery("SELECT * FROM task", null);
        return c;
	}
	
	/**
	 * close database
	 */
	public void closeDB() {
		db.close();
	}
}
